<template>
  <div class="app-container">
    <!-- 搜索和新增区域 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="queryParams.waterQualityIndex"
            placeholder="请输入指标名称"
            clearable
            @clear="handleSearch"
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button icon="Search" @click="handleSearch" />
            </template>
          </el-input>
        </el-col>
      </el-row>
    </el-card>

    <!-- 水质基础设置表格 -->
    <el-card class="mt-1">
      <el-button type="primary" @click="showAddDialog" icon="Plus">新增水质指标</el-button>
      <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
      <el-table
        :data="waterQualityList"
        class="mt-2"
        border
        v-loading="loading"
        :cell-style="{ textAlign: 'center' }"
        :header-cell-style="{ textAlign: 'center', fontWeight: 'bold' }"
      >
        <el-table-column prop="waterQualityIndex" label="水质指标" align="center" />
        <el-table-column prop="indexDescription" label="指标描述" align="center" />
        <el-table-column prop="unit" label="单位" align="center" />
        <el-table-column prop="standardValue" label="标准值" align="center" />
        <el-table-column prop="testMethod" label="检验方法" align="center" />
        <el-table-column prop="samplingContainer" label="采样容器" align="center" />
        <el-table-column prop="lastUpdatedDate" label="最后更新时间" align="center" />
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="mt-2">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增水质基础设置对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="新增水质基础设置"
      width="60%"
      :close-on-click-modal="false"
    >
      <el-form
        :model="addForm"
        label-width="120px"
        :rules="rules"
        ref="addFormRef"
      >
        <el-form-item label="水质指标" prop="waterQualityIndex">
          <el-input v-model="addForm.waterQualityIndex" placeholder="请输入水质指标名称" />
        </el-form-item>
        <el-form-item label="指标描述" prop="indexDescription">
          <el-input v-model="addForm.indexDescription" type="textarea" :rows="2" placeholder="请输入指标描述" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="addForm.unit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="标准值" prop="standardValue">
          <el-input v-model="addForm.standardValue" placeholder="请输入标准值" />
        </el-form-item>
        <el-form-item label="检验方法" prop="testMethod">
          <el-input v-model="addForm.testMethod" placeholder="请输入检验方法" />
        </el-form-item>
        <el-form-item label="检验方法描述" prop="testMethodDescription">
          <el-input v-model="addForm.testMethodDescription" type="textarea" :rows="3" placeholder="请输入检验方法描述" />
        </el-form-item>
        <el-form-item label="采样容器" prop="samplingContainer">
          <el-input v-model="addForm.samplingContainer" placeholder="请输入采样容器" />
        </el-form-item>
        <el-form-item label="容器容量" prop="samplingContainerCapacity">
          <el-input-number v-model="addForm.samplingContainerCapacity" :min="0" :step="0.1" style="width: 100%" />
        </el-form-item>
        <el-form-item label="容器准备要求" prop="samplingContainerPreparation">
          <el-input v-model="addForm.samplingContainerPreparation" type="textarea" :rows="2" placeholder="请输入容器准备要求" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="addForm.remark" type="textarea" :rows="2" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAdd">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑水质基础设置对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑水质基础设置"
      width="60%"
      :close-on-click-modal="false"
    >
      <el-form
        :model="editForm"
        label-width="120px"
        :rules="rules"
        ref="editFormRef"
      >
        <el-form-item label="水质指标" prop="waterQualityIndex">
          <el-input v-model="editForm.waterQualityIndex" placeholder="请输入水质指标名称" />
        </el-form-item>
        <el-form-item label="指标描述" prop="indexDescription">
          <el-input v-model="editForm.indexDescription" type="textarea" :rows="2" placeholder="请输入指标描述" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="editForm.unit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="标准值" prop="standardValue">
          <el-input v-model="editForm.standardValue" placeholder="请输入标准值" />
        </el-form-item>
        <el-form-item label="检验方法" prop="testMethod">
          <el-input v-model="editForm.testMethod" placeholder="请输入检验方法" />
        </el-form-item>
        <el-form-item label="检验方法描述" prop="testMethodDescription">
          <el-input v-model="editForm.testMethodDescription" type="textarea" :rows="3" placeholder="请输入检验方法描述" />
        </el-form-item>
        <el-form-item label="采样容器" prop="samplingContainer">
          <el-input v-model="editForm.samplingContainer" placeholder="请输入采样容器" />
        </el-form-item>
        <el-form-item label="容器容量" prop="samplingContainerCapacity">
          <el-input-number v-model="editForm.samplingContainerCapacity" :min="0" :step="0.1" style="width: 100%" />
        </el-form-item>
        <el-form-item label="容器准备要求" prop="samplingContainerPreparation">
          <el-input v-model="editForm.samplingContainerPreparation" type="textarea" :rows="2" placeholder="请输入容器准备要求" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="editForm.remark" type="textarea" :rows="2" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmEdit">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getWaterQualityList,
  getWaterQualityDetail,
  addWaterQuality,
  updateWaterQuality,
  deleteWaterQuality
} from '@/api/prod_operate/sys_setting/water/water_base'

const { proxy } = getCurrentInstance()

// 加载状态
const loading = ref(false)

// 水质基础设置列表数据
const waterQualityList = ref([])

// 总记录数
const total = ref(0)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  waterQualityIndex: undefined
})

// 新增表单
const addForm = reactive({
  waterQualityIndex: '',
  indexDescription: '',
  unit: '',
  standardValue: '',
  testMethod: '',
  testMethodDescription: '',
  samplingContainer: '',
  samplingContainerCapacity: 0,
  samplingContainerPreparation: '',
  remark: ''
})

// 编辑表单
const editForm = reactive({
  waterQualityId: '',
  waterQualityIndex: '',
  indexDescription: '',
  unit: '',
  standardValue: '',
  testMethod: '',
  testMethodDescription: '',
  samplingContainer: '',
  samplingContainerCapacity: 0,
  samplingContainerPreparation: '',
  lastUpdatedDate: '',
  remark: ''
})

// 对话框控制
const addDialogVisible = ref(false)
const editDialogVisible = ref(false)

// 表单引用
const addFormRef = ref(null)
const editFormRef = ref(null)

// 表单验证规则
const rules = reactive({
  waterQualityIndex: [
    { required: true, message: '请输入水质指标', trigger: 'blur' }
  ],
  indexDescription: [
    { required: true, message: '请输入指标描述', trigger: 'blur' }
  ],
  unit: [
    { required: true, message: '请输入单位', trigger: 'blur' }
  ],
  standardValue: [
    { required: true, message: '请输入标准值', trigger: 'blur' }
  ],
  testMethod: [
    { required: true, message: '请输入检验方法', trigger: 'blur' }
  ],
  samplingContainer: [
    { required: true, message: '请输入采样容器', trigger: 'blur' }
  ]
})

// 初始化数据
const initData = async () => {
  try {
    await fetchWaterQualityList()
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('初始化数据失败')
  }
}

// 获取水质基础设置列表
const fetchWaterQualityList = async () => {
  try {
    loading.value = true
    const res = await getWaterQualityList(queryParams)
    waterQualityList.value = res.rows
    total.value = res.total
  } catch (error) {
    console.error('获取水质基础设置列表失败:', error)
    ElMessage.error('获取水质基础设置列表失败')
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  queryParams.pageNum = 1
  fetchWaterQualityList()
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  fetchWaterQualityList()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  fetchWaterQualityList()
}

// 显示新增对话框
const showAddDialog = () => {
  addForm.waterQualityIndex = ''
  addForm.indexDescription = ''
  addForm.unit = ''
  addForm.standardValue = ''
  addForm.testMethod = ''
  addForm.testMethodDescription = ''
  addForm.samplingContainer = ''
  addForm.samplingContainerCapacity = 0
  addForm.samplingContainerPreparation = ''
  addForm.remark = ''
  addDialogVisible.value = true
}

// 确认新增
const confirmAdd = async () => {
  try {
    await addFormRef.value.validate()
    
    await addWaterQuality(addForm)
    ElMessage.success('新增水质基础设置成功')
    addDialogVisible.value = false
    fetchWaterQualityList()
  } catch (error) {
    console.error('新增水质基础设置失败:', error)
    if (error.message) {
      ElMessage.error(error.message)
    }
  }
}

// 处理编辑
const handleEdit = async (row) => {
  try {
    loading.value = true
    const res = await getWaterQualityDetail(row.waterQualityId)
    Object.assign(editForm, res.data)
    editDialogVisible.value = true
  } catch (error) {
    console.error('获取水质基础设置详情失败:', error)
    ElMessage.error('获取水质基础设置详情失败')
  } finally {
    loading.value = false
  }
}

// 确认编辑
const confirmEdit = async () => {
  try {
    await editFormRef.value.validate()
    
    await updateWaterQuality(editForm)
    ElMessage.success('修改水质基础设置成功')
    editDialogVisible.value = false
    fetchWaterQualityList()
  } catch (error) {
    console.error('修改水质基础设置失败:', error)
    if (error.message) {
      ElMessage.error(error.message)
    }
  }
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该水质基础设置吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteWaterQuality(row.waterQualityId)
      ElMessage.success('删除成功')
      fetchWaterQualityList()
    } catch (error) {
      console.error('删除水质基础设置失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 导出
const handleExport = () => {
  const params = {
    waterQualityIndex: queryParams.waterQualityIndex
  }
  proxy?.download('/operation/web/operationWaterQualityBaseSetting/export', params, `water_quality_${Date.now()}.xlsx`)
}

// 初始化
onMounted(() => {
  initData()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}

.el-select {
  width: 100%;
}

.el-table {
  margin-top: 20px;
}

.el-input-number {
  width: 100%;
}
</style>